# -*- encoding=utf8 -*-
from re import S
import time
# from pytesseract.pytesseract import Output
import win32gui
import mss
import mss.tools
import numpy
import cv2
import pytesseract
import pyautogui
# import win32com.client
import win32api
from time import sleep
from threading import Thread,Lock

WINDOW_TITLE = "公主连结R - MuMu模拟器"

# pytesseract.pytesseract.tesseract_cmd = 'D:\\Tesseract-OCR\\tesseract.exe'

#站位x坐标
dx = {}
#站位y坐标
dy = 0

#模拟器位置信息
top = 0
left = 0

#检测时间的区域
monitor = {}

def getGameWindow():
    # FindWindow(lpClassName=None, lpWindowName=None)  窗口类名 窗口标题名
    window = win32gui.FindWindow(None, WINDOW_TITLE)

    # 没有定位到窗体
    while not window:
        print('获取窗口失败，10秒后重新尝试')
        time.sleep(10)
        window = win32gui.FindWindow(None, WINDOW_TITLE)
    
    # shell = win32com.client.Dispatch("WScript.Shell")
    # shell.SendKeys('%')
    win32api.keybd_event(13, 0, 0, 0)
    win32gui.SetForegroundWindow(window) #窗口置顶

    #获取句柄窗口的大小信息

    global left,top
    left, top, right, bot= win32gui.GetWindowRect(window)

    #初始化站位坐标
    global dx,dy
    dx = {
        5:left+321,
        4:left+481,
        3:left+641,
        2:left+801,
        1:left+961
    }
    dy = top+631

    #截图区域
    global monitor
    monitor = {"top": top+57, "left": left+1075, "width": 48, "height": 23} 

    print("窗口捕获成功")

    # print(left, top, right, bot)
    # print(left+1075, top+57, right, bot)

# getGameWindow()


#存放轴的大列表
L1=[]

#读取文件中的轴
def read():
    global L1
    with open("operation.txt","r") as f:
        for line in f.readlines():
            line = line.strip('\n')
            line2 = [line.split()[0],int(line.split()[1])]
            L1.append(line2)
        # print(L1)
        print("时轴读取完毕")


#点击次数
clicks = 400
#点击间隔
interval = 0.01

#当前轴点击的站位
target = 0

#连点
def touch():
    # if n == True:
    #     sleep(1)
    #     print("该线程已开启1s睡眠")
    pyautogui.click(x=dx[target],y=dy,clicks=clicks,interval=interval,button='left')


#检测
#todo：点auto，每条时间单独分配点击次数，每个站位一条线程;尝试用按键代替鼠标
def shot():

    #点击开始战斗
    # pyautogui.click(x=left+1115,y=top+637,clicks=5,interval=0.1,button='left')
    print("开始战斗")
    sleep(5)

    global target
    o_time = ""


    with mss.mss() as sct:
        
        while True:
                # output = "sct-{top}x{left}_{width}x{height}.png".format(**monitor)
                # sct_img = sct.grab(monitor)
                # mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
                # print(output)
                
            img = numpy.array(sct.grab(monitor))
            img = cv2.resize(img,(288,138),interpolation=cv2.INTER_LINEAR)
            # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            # binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10)
            # cv2.imwrite("tmp.png",binary)
            cur_time = pytesseract.image_to_string(img,config="--psm 6 --oem 1 -c tessedit_char_whitelist=0123456789:").rstrip()
            # print(time == L1[0][0])
            if cur_time == L1[0][0]: #当前时间与时轴时间一致
                if o_time == cur_time: #如果上一次时间与当前时间相同
                    target = L1[0][1]
                    o_time = L1[0][0] #保存当前时间
                    L1.pop(0)
                    print("睡眠1.5s后开启一条点击线程")
                    sleep(1.5)
                    Thread(target=touch).start()
                else:
                    target = L1[0][1]
                    o_time = L1[0][0] #保存当前时间
                    L1.pop(0)
                    print("开启一条点击线程")
                    Thread(target=touch).start()
                if not L1:
                    print("所有操作执行完毕")
                    break
            print(cur_time)

# shot()

def main():
    # getGameWindow()
    # shot()
    global clicks
    while True:
        print("请输入每次连点次数[默认为400](回车跳过):",end="")
        n = input()
        if n == "":
            print("次数为：400")
            break
        elif isinstance(n,int):
            print("请输入整数！")
            continue
        else:
            clicks = int(n)
            print("次数设置为："+str(clicks))
            break
    
    read()
    print("---------------------------------")
    print("回车开始，期间不允许移动鼠标:",end='')
    if input() == '':
        getGameWindow()
        shot()

if __name__ == '__main__':
    main()